{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 模型调参"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 网格化调参\n",
    "\n",
    "sklearn GridSearchCV"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-09-27T12:53:34.718090Z",
     "start_time": "2019-09-27T12:53:34.712108Z"
    }
   },
   "outputs": [],
   "source": [
    "def model_params_tuning(X_train, y_train, model, param=None):\n",
    "    \"\"\"\n",
    "    交叉验证，参数调优，回归 mse 目标函数例子，返回最优模型\n",
    "    :param X_train:\n",
    "    :param y_train:\n",
    "    :param model:\n",
    "    :param param:\n",
    "    :return:\n",
    "    \"\"\"\n",
    "    grid_search = GridSearchCV(model, param, cv=5, scoring='neg_mean_squared_error')\n",
    "    grid_search.fit(X_train, y_train)\n",
    "\n",
    "    print(\"Best parameters:{}\".format(grid_search.best_params_))\n",
    "    print(\"Best score on train set:{:.2f}\".format(grid_search.best_score_))\n",
    "\n",
    "    means = grid_search.cv_results_['mean_test_score']\n",
    "    stds = grid_search.cv_results_['std_test_score']\n",
    "    for mean, std, params in zip(means, stds, grid_search.cv_results_['params']):\n",
    "        print(\"%0.3f (+/-%0.03f) for %r\"\n",
    "              % (mean, std * 2, params))\n",
    "    return grid_search.best_estimator_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import mean_squared_error\n",
    "from sklearn import linear_model\n",
    "from sklearn.model_selection import GridSearchCV\n",
    "\n",
    "# 回归模型\n",
    "lr = linear_model.LinearRegression()\n",
    "lr = linear_model.Ridge(alpha=0.1)\n",
    "# 参数调整\n",
    "lr_params = {'alpha': np.linspace(0.1, 10, 20)}\n",
    "lr = model_params_tuning(X_train, y_train, lr, lr_params)\n",
    "# # 模型训练\n",
    "lr.fit(X_train_lr, y_train)\n",
    "\n",
    "lr_f_imp = pd.Series(lr.coef_, index=X_train_lr.columns.values)\n",
    "print(lr_f_imp.sort_values(ascending=False).to_string())\n",
    "\n",
    "print('train mse: ', mean_squared_error(y_train, lr.predict(X_train_lr)))\n",
    "y_pred = lr.predict(X_test_lr)\n",
    "print('test mse: ', mean_squared_error(y_test, y_pred))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": true,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
